<template>
  <div class="puzzle-container" v-show="isVerificationShow">
    <!-- 头部 -->
    <div class="puzzle-header">
      <span class="puzzle-header-left">拖动下方滑块完成拼图</span>
      <div>
        <span class="re-btn iconfont icon-shuaxin" @click="refreshImg"></span>
        <span
          class="close-btn iconfont icon-guanbi"
          @click="closeVerificationBox"
        ></span>
      </div>
    </div>

    <div
      class="puzzle-body"
      :style="{
        width: dataWidth + 'px',
      }"
    >
      <div
        class="puzzle-bg"
        :style="{
          width: dataWidth + 'px',
          height: dataHeight + 'px',
        }"
      >
        <img
          :src="imgRandom"
          :style="{
            width: dataWidth + 'px',
            height: dataHeight + 'px',
          }"
        />
        <canvas
          id="puzzle-box"
          ref="puzzleBox"
          :width="dataWidth"
          :height="dataHeight"
        ></canvas>
      </div>
      <div
        class="puzzle-lost-box"
        :style="{
          left: leftNum + 'px',
          width: dataWidth + 'px',
          height: dataHeight + 'px',
        }"
      >
        <canvas
          id="puzzle-shadow"
          ref="puzzleShadow"
          :width="dataWidth"
          :height="dataHeight"
        ></canvas>
        <canvas
          id="puzzle-lost"
          ref="puzzleLost"
          :width="dataWidth"
          :height="dataHeight"
        ></canvas>
      </div>
      <!-- 提示信息 -->
      <div class="ver-tips" :class="{ 'slider-tips': displayTips }">
        <div v-if="verification">
          <i style="background-position: -4px -1207px"></i>
          <span style="color: #42ca6b">验证通过</span>
          <span></span>
        </div>
        <div v-else>
          <i style="background-position: -4px -1229px"></i>
          <span style="color: red">验证失败:</span>
          <span style="margin-left: 4px">拖动滑块将悬浮图像正确拼合</span>
        </div>
      </div>
    </div>

    <div class="slider-container" :style="{ width: dataWidth + 'px' }">
      <div class="slider-bar"></div>
      <div
        class="slider-btn"
        ref="sliderBtn"
        @mousedown.stop="startMove"
        @touchstart.stop="startMove"
      >
        <d-arrow-right class="slide-btn-icon" />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, toRefs, onMounted, watch, nextTick } from "vue";

export default {
  name: "puzzleVerification",
  emits: ["update:modelValue", "success", "fail", "close"],
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    // 画布图片的尺寸
    width: {
      type: Number,
      default: 260,
    },
    height: {
      type: Number,
      default: 120,
    },
    // 图集
    puzzleImgList: {
      type: Array,
      default: () => [
        "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1551244602306&di=5b40d29f1de52815d2643ce3eb3f6d3b&imgtype=0&src=http%3A%2F%2Fimg1.3lian.com%2F2015%2Fa1%2F38%2Fd%2F168.jpg",
        "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1551244644208&di=3f09dbe3476994f15ed207e4d0c008ef&imgtype=0&src=http%3A%2F%2Fpic3.16pic.com%2F00%2F47%2F90%2F16pic_4790939_b.jpg",
        "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1551244821054&di=bf03257cfaf9d0a0f020e7f1363cf5f8&imgtype=0&src=http%3A%2F%2Fpic.58pic.com%2F58pic%2F15%2F11%2F96%2F88W58PIC7Y2_1024.jpg",
      ],
    },
    // 滑块的大小
    blockSize: {
      type: Number,
      default: 40,
    },
    // 误差
    deviation: {
      type: Number,
      default: 4,
    },
    // 滑块的圆角大小
    blockRadius: {
      type: Number,
      default: 4,
    },
    // 滑块随机出现的范围
    wraperPadding: {
      type: Number,
      default: 20,
    },
    // 滑块形状 square  puzzle
    blockType: {
      type: String,
      default: "puzzle",
      validator: (val) => {
        return ["puzzle", "square"].includes(val);
      },
    },
  },
  setup(props, context) {
    const state = reactive({
      isVerificationShow: false,
      moveStart: 0,
      displayTips: false,
      verification: false,
      randomX: 0,
      randomY: 0,
      imgRandom: "",
      leftNum: 0,
      // 画布的宽度
      dataWidth: 0,
      // 画布的高度
      dataHeight: 0,
      // 滑块的大小
      puzzleSize: 0,
      // 误差
      deviationValue: 0,
      // 滑块的圆角大小
      radius: 0,
      // 滑块随机出现的范围
      padding: 0,
      puzzleBoxCtx: null,
      puzzleLostCtx: null,
      puzzleShadowCtx: null,
    });

    const puzzleBox = ref(null);
    const puzzleLost = ref(null);
    const puzzleShadow = ref(null);
    const sliderBtn = ref(null);

    /* 通过重置画布尺寸清空画布，这种方式更彻底 */
    const clearCanvas = () => {
      state.puzzleBoxCtx.clearRect(0, 0, state.dataWidth, state.dataHeight);
      state.puzzleLostCtx.clearRect(0, 0, state.dataWidth, state.dataHeight);
      state.puzzleShadowCtx.clearRect(0, 0, state.dataWidth, state.dataHeight);
    };

    // 画方形滑块
    const drawSquare = (ctx, X, Y, radius, puzzleSize) => {
      ctx.arc(X + radius, Y + radius, radius, Math.PI, (Math.PI * 3) / 2);
      ctx.lineTo(puzzleSize - radius + X, Y);
      ctx.arc(
        puzzleSize - radius + X,
        radius + Y,
        radius,
        (Math.PI * 3) / 2,
        Math.PI * 2
      );
      ctx.lineTo(puzzleSize + X, puzzleSize + Y - radius);
      ctx.arc(
        puzzleSize - radius + X,
        puzzleSize - radius + Y,
        radius,
        0,
        (Math.PI * 1) / 2
      );
      ctx.lineTo(radius + X, puzzleSize + Y);
      ctx.arc(
        radius + X,
        puzzleSize - radius + Y,
        radius,
        (Math.PI * 1) / 2,
        Math.PI
      );
    };

    const drawPuzzle = (ctx, X, Y, d) => {
      ctx.moveTo(X, Y);
      ctx.lineTo(X + d, Y);
      ctx.bezierCurveTo(X + d, Y - d, X + 2 * d, Y - d, X + 2 * d, Y);
      ctx.lineTo(X + 3 * d, Y);
      ctx.lineTo(X + 3 * d, Y + d);
      ctx.bezierCurveTo(
        X + 2 * d,
        Y + d,
        X + 2 * d,
        Y + 2 * d,
        X + 3 * d,
        Y + 2 * d
      );
      ctx.lineTo(X + 3 * d, Y + 3 * d);
      ctx.lineTo(X, Y + 3 * d);
    };

    /* 画布初始化 */
    const initCanvas = () => {
      clearCanvas();
      const width = state.dataWidth;
      const height = state.dataHeight;
      const puzzleSize = state.puzzleSize;
      const padding = state.padding;
      const radius = state.radius;
      const puzzleBoxCtx = state.puzzleBoxCtx;
      const puzzleLostCtx = state.puzzleLostCtx;
      const puzzleShadowCtx = state.puzzleShadowCtx;
      const minPuzzleX = padding + puzzleSize;
      const maxPuzzleX = width - padding - puzzleSize - puzzleSize / 6;
      const maxPuzzleY = padding;
      const minPuzzleY = height - padding - puzzleSize - puzzleSize / 6;
      state.randomX = Math.round(
        Math.random() * (maxPuzzleX - puzzleSize) + minPuzzleX
      );
      state.randomY = Math.round(Math.random() * maxPuzzleY + minPuzzleY);
      const X = state.randomX;
      const Y = state.randomY;
      state.leftNum = -X + 10;
      const d = puzzleSize / 3;
      puzzleBoxCtx.save();
      puzzleBoxCtx.globalCompositeOperation = "xor";
      puzzleBoxCtx.shadowBlur = 10;
      puzzleBoxCtx.shadowColor = "#fff";
      puzzleBoxCtx.shadowOffsetX = 3;
      puzzleBoxCtx.shadowOffsetY = 3;
      puzzleBoxCtx.fillStyle = "rgba(0,0,0,0.7)";
      puzzleBoxCtx.beginPath();
      puzzleBoxCtx.lineWidth = "1";
      puzzleBoxCtx.strokeStyle = "rgba(0,0,0,0)";
      if (props.blockType === "square") {
        drawSquare(puzzleBoxCtx, X, Y, radius, puzzleSize);
      } else {
        drawPuzzle(puzzleBoxCtx, X, Y, d);
      }
      puzzleBoxCtx.closePath();
      puzzleBoxCtx.fill();
      puzzleBoxCtx.stroke();
      puzzleBoxCtx.restore();

      const img = new Image();
      img.src = state.imgRandom;
      img.onload = function () {
        puzzleLostCtx.save();
        puzzleLostCtx.beginPath();
        puzzleLostCtx.strokeStyle = "rgba(0,0,0,0)";
        if (props.blockType === "square") {
          drawSquare(puzzleLostCtx, X, Y, radius, puzzleSize);
        } else {
          drawPuzzle(puzzleLostCtx, X, Y, d);
        }
        puzzleLostCtx.closePath();
        puzzleLostCtx.stroke();
        puzzleLostCtx.shadowBlur = 10;
        puzzleLostCtx.shadowColor = "black";
        // 此方法下面的部分为待剪切区域，上面的部分为剪切区域
        puzzleLostCtx.clip();
        puzzleLostCtx.drawImage(img, 0, 0, width, height);
        puzzleLostCtx.restore();
      };

      puzzleShadowCtx.save();
      puzzleShadowCtx.beginPath();
      puzzleShadowCtx.lineWidth = "1";
      puzzleShadowCtx.strokeStyle = "rgba(0,0,0,0)";
      if (props.blockType === "square") {
        drawSquare(puzzleShadowCtx, X, Y, radius, puzzleSize);
      } else {
        drawPuzzle(puzzleShadowCtx, X, Y, d);
      }
      puzzleShadowCtx.closePath();
      puzzleShadowCtx.stroke();
      puzzleShadowCtx.shadowBlur = 20;
      puzzleShadowCtx.shadowColor = "black";
      puzzleShadowCtx.fill();
      puzzleShadowCtx.restore();
    };

    /* 关闭验证 */
    const closeVerificationBox = () => {
      state.isVerificationShow = false;
      context.emit("close");
    };

    /* 刷新 */
    const refreshImg = () => {
      const imgRandomIndex = Math.round(
        Math.random() * (props.puzzleImgList.length - 1)
      );
      state.imgRandom = props.puzzleImgList[imgRandomIndex];
      initCanvas();
    };

    /* 全局绑定滑块移动与滑动结束，移动过程中鼠标可在页面任何位置 */
    const addMouseMoveListener = () => {
      document.addEventListener("mousemove", moving, true);
      document.addEventListener("touchmove", moving, true);
      document.addEventListener("mouseup", moveEnd, true);
      document.addEventListener("touchend", moveEnd, true);
    };

    const removeMouseMoveListener = () => {
      document.removeEventListener("mousemove", moving);
      document.removeEventListener("touchmove", moving);
      document.removeEventListener("mouseup", moveEnd);
      document.removeEventListener("touchend", moveEnd);
    };

    /* 按住滑块后初始化移动监听，记录初始位置 */
    const startMove = (e) => {
      e = e || window.event;
      sliderBtn.value.style.backgroundPosition = "0 -216px";
      state.moveStart = e.pageX || e.targetTouches[0].pageX;
      addMouseMoveListener();
    };

    /* 滑块移动 */
    const moving = (e) => {
      e = e || window.event;
      const moveX = e.pageX || e.targetTouches[0].pageX;
      const d = moveX - state.moveStart;
      const w = state.dataWidth;
      const puzzleSize = state.puzzleSize;
      const padding = state.padding;
      if (state.moveStart === "") {
        return "";
      }
      if (d < 0 || d > w - padding - puzzleSize) {
        return "";
      }
      sliderBtn.value.style.left = d + "px";
      sliderBtn.value.style.transition = "inherit";
      puzzleLost.value.style.left = d + "px";
      puzzleLost.value.style.transition = "inherit";
      puzzleShadow.value.style.left = d + "px";
      puzzleShadow.value.style.transition = "inherit";
    };

    /* 移动结束，验证并回调 */
    const moveEnd = (e) => {
      e = e || window.event;
      const moveEndX = (e.pageX || e.changedTouches[0].pageX) - state.moveStart;
      const verNum = state.randomX - 10;
      const deviationValue = state.deviationValue;
      const minLeft = verNum - deviationValue;
      const maxLeft = verNum + deviationValue;
      if (state.moveStart !== "") {
        if (maxLeft > moveEndX && moveEndX > minLeft) {
          state.displayTips = true;
          state.verification = true;
          setTimeout(function () {
            state.displayTips = false;
            initCanvas();
            /* 成功的回调函数 */
            context.emit("success");
            state.isVerificationShow = false;
          }, 500);
        } else {
          state.displayTips = true;
          state.verification = false;
          setTimeout(function () {
            state.displayTips = false;
            initCanvas();
            /* 失败的回调函数 */
            context.emit("fail");
          }, 800);
        }
      }
      if (sliderBtn.value && puzzleLost.value && puzzleShadow.value) {
        setTimeout(function () {
          sliderBtn.value.style.left = 0;
          sliderBtn.value.style.transition = "left 0.5s";
          puzzleLost.value.style.left = 0;
          puzzleLost.value.style.transition = "left 0.5s";
          puzzleShadow.value.style.left = 0;
          puzzleShadow.value.style.transition = "left 0.5s";
        }, 400);
        sliderBtn.value.style.backgroundPosition = "0 -84px";
      }
      state.moveStart = "";
      removeMouseMoveListener();
    };

    watch(
      () => state.isVerificationShow,
      (newVal) => {
        context.emit("update:modelValue", newVal);
      }
    );

    watch(
      () => props.modelValue,
      (newVal) => {
        state.isVerificationShow = newVal;
      },
      { immediate: true }
    );

    const initData = () => {
      // 随机显示一张图片
      const imgRandomIndex = Math.round(
        Math.random() * (props.puzzleImgList.length - 1)
      );
      state.imgRandom = props.puzzleImgList[imgRandomIndex];
      state.puzzleSize = Number(props.blockSize);
      state.deviationValue = Number(props.deviation);
      state.radius = Number(props.blockRadius);
      state.dataWidth = Number(props.width);
      state.dataHeight = Number(props.height);
      state.padding = Number(props.wraperPadding);
    };

    initData();
    onMounted(() => {
      state.puzzleBoxCtx = puzzleBox.value.getContext("2d");
      state.puzzleLostCtx = puzzleLost.value.getContext("2d");
      state.puzzleShadowCtx = puzzleShadow.value.getContext("2d");
      initCanvas();
    });

    return {
      puzzleBox,
      puzzleLost,
      puzzleShadow,
      sliderBtn,
      closeVerificationBox,
      refreshImg,
      startMove,
      moving,
      moveEnd,
      ...toRefs(state),
    };
  },
};
</script>

<style scoped>
.puzzle-body {
  position: relative;
  overflow: hidden;
}

.puzzle-bg {
  position: relative;
}

.ver-tips {
  position: absolute;
  left: 0;
  bottom: -22px;
  background: rgba(255, 255, 255, 0.9);
  height: 22px;
  line-height: 22px;
  font-size: 12px;
  width: 100%;
  margin: 0;
  text-align: left;
  padding: 0 8px;
  transition: all 0.4s;
}

.slider-tips {
  bottom: 0;
}

.ver-tips i {
  display: inline-block;
  width: 22px;
  height: 22px;
  vertical-align: top;
  background-image: url(./sprite.3.2.0.png);
  background-position: -4px -1229px;
}

.ver-tips span {
  display: inline-block;
  vertical-align: top;
  line-height: 22px;
  color: #455;
}

.active-tips {
  display: block;
}

.hidden {
  display: none;
}

.puzzle-container {
  display: inline-block;
  position: relative;
  padding: 15px 15px 28px;
  border: 1px solid #ddd;
  background: #ffffff;
  border-radius: 16px;
}

.puzzle-header {
  display: flex;
  justify-content: space-between;
  margin: 5px 0;
}

.puzzle-header-left {
  color: #333;
}

.re-btn,
.close-btn {
  font-size: 16px;
  cursor: pointer;
  color: #666;
}

.re-btn:hover {
  color: #67c23a;
}

.close-btn:hover {
  color: #f56c6c;
}

.close-btn {
  margin-left: 5px;
}

.slider-container {
  position: relative;
  margin: 10px auto 0;
  min-height: 15px;
}

.slider-bar {
  height: 10px;
  border: 1px solid #c3c3c3;
  border-radius: 5px;
  background: #e4e4e4;
  box-shadow: 0 1px 1px rgba(12, 10, 10, 0.2) inset;
  position: absolute;
  width: 100%;
  top: 7px;
}

#puzzle-box {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 22;
}

#puzzle-shadow {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 22;
}

#puzzle-lost {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 33;
}

.puzzle-lost-box {
  position: absolute;
  width: 260px;
  height: 116px;
  left: 0;
  top: 0;
  z-index: 111;
}

@font-face {
  font-family: "iconfont";
  src: url("../assets/icon-font/iconfont.eot?t=1565160368550"); /* IE9 */
  src: url("../assets/icon-font/iconfont.eot?t=1565160368550#iefix")
      format("embedded-opentype"),
    /* IE6-IE8 */
      url("data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAANUAAsAAAAAByQAAAMIAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCCfAqCFIIkATYCJAMMCwgABCAFhG0HOhtkBsi+QDw2JxWVhBKVFukepjkT9iz2vr6/fAq8RxAPz4+9O/e9O9WkGj15Fk3LQ/NCJ41QaVASVSzTSJ7E2p//a/4CvASvALwTjbaVddq9o71hlfDegDawAW//1zQFGqAwEaokh6yK8jD/9/c4lxuw3PPkdI3ZegseIJGz/1WKn5AESUiaSApHHzJ2/2uCAT/S0Iz7q0i8eCKrBLgEQJauMPX/uZzeKPH5KSuXuSYd9aI4DiigvbFNViAJeovsrkAs8jyBdmME8ODibgRNyZwWiIdGO9DM+KXkU61Cc8XaFI9p0loe6Q3gNvh+fKdFk6KpMuceX5/7cPTJ/Tfy4spDEIxnBb+JihVAEueV9kOVKL4Ca1dZq6YAKXljibz/PCFRiGZmcSdYIInCJw6Toid+iM6+oYJmd5A8BW4pefDQFKWzc2SkXpr+P1LN9+L/JeF4UsZPUGWa/nUPMypPfme7Do2j785+zvL4Z37s1l/wcAEwhNPJqPMcHgerCdZ/wbrLlYRrg2tSMZ45fpHJLQ7humLaL9WW9r64yBa+7D3UcBOs/3jDHKz7+MTzgPkExVfzZnHa3qveHHJTfVjsFjh5X99QxlP8cdhYHOyY+Fmy4BUXoLG2ngiSbe2xv/AbW/8ptNb3/tiQ4MN+w2saBeoEoFUBLHjnAmBTaiLTUFPhO3zDUa2nvAqYK7g0MN39vv3VQzeXDK2GEihajELVagZN8go06bAKzVptQ7tlzuYOAyoqItuwZIgg9LpC0e05VL1eaJI/0GTYD5r1RgXaXcb2nh3mwiydMjlCPrpPaLwkVrZJlsLSAekidDgtCigT4tyEsCcp+dQlxcRjLMjvdV9EoeIkwgt0GYVhgiknc/KkPRNJdzpyXPWmtpdEsGQfIw5BfMj3BGU8iZjyOoulwucHiFYIObiBUGWfICxnekcqiQJAL+UxiHAt11Td0/pqhIJiLBFBNrKS0IonUKl61BzxiLa0RzS1QyatYqi8Pb8yer5d0M7co0aJGqn5TuHErmnksyD2aGIA")
      format("woff2"),
    url("../assets/icon-font/iconfont.woff?t=1565160368550") format("woff"),
    url("../assets/icon-font/iconfont.ttf?t=1565160368550") format("truetype"),
    /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
      url("../assets/icon-font/iconfont.svg?t=1565160368550#iconfont")
      format("svg"); /* iOS 4.1- */
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-guanbi:before {
  content: "\f01f1";
}

.icon-shuaxin:before {
  content: "\e609";
}

.slider-btn {
  position: absolute;
  width: 44px;
  height: 26px;
  left: 0;
  top: 0px;
  z-index: 12;
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 15px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.slide-btn-icon {
  color: #ccc;
  height: 24px;
  width: 24px;
}
</style>
